<template>
  <div class="container upload-container">
    <div class="upload-file-box" v-loading="uploadLoading" @mouseenter="toolbarShow=true" @mouseleave="toolbarShow=false">
      <el-upload
        ref="uploadEl"
        :disabled="disabled"
        :headers="headers"
        :action="uploadFilesUrl"
        v-bind="$attrs"
        v-on="$listeners"
        class="image-uploader"
        :show-file-list="false"
        :before-upload="beforeAvatarUpload"
        :on-success="successUpload"
        :on-error="errorUpload">
        <i class="iconfont df-iconweb-icon- image-uploader-icon"></i>
      </el-upload>
      <viewer v-if="imageUrl && urlType == 'image'" :images="imageUrlList"> 
        <img :src="imageUrl" class="image-viewer" title="点击图片预览">
      </viewer>
      <a v-if="imageUrl && urlType != 'image'" :href="imageUrl" class="image-viewer" :class="urlType+'-view'" title="点击图片下载" download></a>
      <transition name="slide-fade">
        <div v-if="imageUrl && toolbarShow && !disabled" class="image-toolbar">
          <div class="image-toolbar-box del">
            <i class="iconfont df-iconshanchu image-toolbar-del" title="删除" @click="handleDel"></i>
          </div>
          <div class="image-toolbar-box update">
            <i class="iconfont df-iconluru image-toolbar-update" title="重新上传" @click="handleUpdate"></i>
          </div>
        </div>
      </transition>
    </div>
    <div class="upload-title-box" :title="label || item.lable">
      <el-tooltip class="item" effect="dark" content="必填" placement="top">
        <i class="el-icon-star-on" v-if="required || required === 1 || item.required || item.required === 1" style="color: #F56C6C;"></i>
      </el-tooltip>
      <label for="" :title="label || item.label">{{label || item.label}}</label>
    </div>
  </div>
</template>

<script>
import { api, objectStore } from '@/api/common';
import { matchType } from '@/util/upload';

export default {
  props: {
    item: {
      type: Object,
      required: true
    },
    disabled: Boolean,
    value: String,
    label: String,
    required: Boolean
  },
  data() {
    return {
      imageUrlList: [],
      imageUrl: '',
      urlType: 'image',
      uploadLoading: false,
      toolbarShow: false,
      headers:{
        uid:this.$store.getters.userInfo.id,
        token:this.$store.getters.token
      }
    };
  },
  watch: {
    // imageUrl(val) {
    //   console.log(val)
    // },
    value(val) {
      console.log('123',val)
      this.imageUrlList = []
      if (this.item.hasOwnProperty('objStore') && !this.item.objStore) {
        this.imageUrl = val
        this.imageUrlList.push(val)
      } else {
        if (val != '') {
          this.getFile(val)
        } else {
          this.imageUrl = ''
        }
      }
    }
  },
  created() {
    if (this.value && this.value != '') {
      this.getFile(this.value)
    } else {
      this.imageUrl = ''
    }
  },
  computed: {
    fileInputRefs () {
      // 上传组件中的 input
      return this.$refs['uploadEl'].$refs['upload-inner'].$refs['input']
    },
    uploadFilesUrl () {
      let _this = this,
        _url = ''

      if (_this.item.hasOwnProperty('uploadType') && _this.item['uploadType'] === 'objectStore') {
        if (_this.item.hasOwnProperty('uploadUrl') && _this.item['uploadUrl'] !== '') {
          _url = objectStore[_this.item.uploadUrl]
        } else {
          if (_this.item.hasOwnProperty('fileType') && _this.item['fileType'].length === 1 && _this.item['fileType'][0] === 'image') {
            _url = objectStore['upload_img']
          } else {
            _url = objectStore['upload_file']
          }
        }
      } else {
        if (_this.item.hasOwnProperty('uploadUrl') && _this.item['uploadUrl'] !== '') {
          _url = api[_this.item.uploadUrl]
        } else {
          if (_this.item.hasOwnProperty('fileType') &&  _this.item['fileType'].length === 1 && _this.item['fileType'][0] === 'excel') {
            _url = api['upload_excel']
          } else {
            _url = api['upload_file']
          }
        }
      }

      return _url
    }
  },
  methods: {
    handleUpdate () {
      this.$refs.uploadEl.$refs['upload-inner'].$refs.input.click()
    },
    //上传之前操作
    beforeAvatarUpload(file) {
      console.log(file);
      this.uploadLoading = true

      //判断上传文件大小
      if(this.item.size && this.item.size != '' && this.item.size != 0){
        const isLt2M = file.size / 1024 < Number(this.item.size);
        let isMinSize = true
        if (this.item.hasOwnProperty('minsize')) {
          isMinSize = file.size / 1024 > Number(this.item.minsize);
        }
        if (!isLt2M || !isMinSize) {
          let numStr = this.item.size + 'KB'
          if(Number(this.item.size) / 1024  > 0){
            numStr = Math.round((Number(this.item.size) / 1024) * 100) / 100 + 'MB'
          }
          if (this.item.hasOwnProperty('sizeError')) {
            this.$message.error(this.item.sizeError);
          } else if(this.item.hasOwnProperty('minsize')) {
            let minnumStr = this.item.minsize + 'KB'
            if(Number(this.item.minsize) / 1024  > 0){
              minnumStr = Math.round((Number(this.item.minsize) / 1024) * 100) / 100 + 'MB'
            }
            this.$message.error('上传文件大小不能小于 '+ minnumStr +',不能超过 ' + numStr + '!');
          } else {
            this.$message.error('上传文件大小不能超过 ' + numStr + '!');
          }
          this.uploadLoading = false
          return false
        }
      }
      //判断上传文件类型
      if(this.item.fileType.length > 0){
        let matchFileType = matchType(file.name)
        const isFileType = matchFileType.indexOf(this.item.fileType.join(',')) != -1
        if (!isFileType) {
          this.$message.error('上传文件格式不正确!');
          this.uploadLoading = false
          return isFileType
        }
      }

      if (this.item.hasOwnProperty('fileTypeSuffix') && this.item.fileTypeSuffix.length > 0) {
        let suffix = ''
        try {
          var flieArr = file.name.split('.');
          suffix = flieArr[flieArr.length - 1];
        } catch (err) {
          suffix = '';
        }
        const isFileTypeSuffix = suffix.indexOf(this.item.fileTypeSuffix.join(',')) != -1
        if (!isFileTypeSuffix) {
          this.$message.error('上传文件格式不正确,为 '+this.item.fileTypeSuffix.join(',')+' 格式!');
          this.uploadLoading = false
          return isFileTypeSuffix
        }
      }
      
      return true
    },
    successUpload(response) {
      console.log(response);
      this.uploadLoading = false
      if(response.code === 10000){
        this.$message.success(response.message);
        this.imageUrl = response.data.src;
        this.urlType = matchType(response.data.key)
        this.$emit('uploadChange',{ key: this.item.key, val: response.data.key, item: this.item, data: response.data })
        if (this.item.hasOwnProperty('setValue')) {
          this.$emit('uploadChange',{ key: this.item.setValue, val: response.data[this.item.setValueKey] })
        }
      }else{
        this.$message.error(response.message);
      }
    },
    errorUpload(err) {
      console.log(err);
      this.uploadLoading = false
      this.$message.error(err);
    },
    handleDel () {
      this.$confirm(`确定删除【${ this.label || this.item.label }】附件？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$emit('uploadChange',{ key: this.item.key, val: '', item: this.item })
        if (this.item.hasOwnProperty('setValue')) {
          this.$emit('uploadChange',{ key: this.item.setValue, val: '' })
        }
        this.imageUrl = ''
      }).catch(()=>{})
    },
    getFile (key) {
      let _this = this
      _this.imageUrlList = []
      _this.axios.post(objectStore.getObjectChannel, { key:key }).then((res)=>{
        console.log(res)
        if(res.data.code == 10000){
          _this.imageUrl = res.data.data.src
          _this.imageUrlList.push(_this.imageUrl)
          _this.urlType = matchType(key)
        }else{
          _this.imageUrl = ''
          _this.urlType = 'image'
          _this.$message({
            showClose: false,
            message: res.data.message,
            type: 'error'
          });
        }
      }).catch((err)=>{
        _this.imageUrl = ''
        _this.urlType = 'image'
        console.log('调用失败',err)
      })
    }
  }
}
</script>

<style scoped="scoped" lang="scss">
  .upload-container{
    height: 200px;
    width: 240px;
    .upload-file-box {
      position: relative;
      margin: 0 auto;
      width: 95%;
      height: 160px;
      background: rgba(240,240,240,1);
      .image-uploader {
        position: absolute;
        top: 0;
        left: 0;
        z-index: 1;
        width: 100%;
        .image-uploader-icon {
          font-size: 43px;
          color: #8c939d;
          width: 100%;
          height: 160px;
          line-height: 160px;
          text-align: center;
        }
      }
      .image-viewer {
        position: absolute;
        top: 0;
        left: 0;
        z-index: 2;
        width: 100%;
        height: 160px;
        display: block;
        cursor: pointer;
      }
      .no-image-viewer {
        display: block;
        position: absolute;
        top: 0;
        left: 0;
        z-index: 2;
        width: 100%;
        height: 160px;
        line-height: 160px;
        text-align: center;
        background: #f0f0f0;
      }
      .image-toolbar {
        position: absolute;
        top: 0;
        left: 0;
        z-index: 3;
        width: 100%;
        height: 40px;
        line-height: 40px;
        // background: rgba(255, 255, 255, .2);
        .image-toolbar-box {
          float: right;
          margin: 4px 8px 0 0;
          width: 32px;
          height: 32px;
          line-height: 32px;
          text-align: center;
          border-radius:2px;
          font-size: 16px;
          cursor: pointer;
        }
        .image-toolbar-box.del {
          background: #4285F4;
          color: #fff;
        }
        .image-toolbar-box.update {
          background: #fff;
          color: #333;
        }
      }
    }
    .upload-title-box {
      margin: 0 auto;
      width: calc(95% - 2px);
      height: 39px;
      line-height: 39px;
      border:1px solid rgba(221,221,221,1);
      border-top: none;
      text-align: center;
      text-overflow:ellipsis; 
      overflow:hidden;
      white-space:nowrap;
    }
    .slide-fade-enter-active {
      transition: all .3s ease;
    }
    .slide-fade-leave-active {
      transition: all .8s cubic-bezier(1.0, 0.5, 0.8, 1.0);
    }
    .slide-fade-enter, .slide-fade-leave-to
    /* .slide-fade-leave-active for below version 2.1.8 */ {
      transform: translateY(-40px);
      opacity: 0;
    }
  }
</style>
